import { Component, ViewChild, ComponentFactoryResolver, Input, OnInit, ViewContainerRef, SimpleChanges } from '@angular/core';
import { EventService } from '../../../shared/service/event.service';
import { TabsService } from '../../../shared/service/tabs.service';

import { ComItem } from '../com-item';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';

@Component({
    selector: 'app-subtab1',
    template: '<section>\n' +
        '<ng-template appSubAnchor #dynamicComponent></ng-template>\n' +
        '</section>'
})

export class SubComs1Component implements OnInit { // slide缓存
    @Input() subComs: ComItem[];
    @ViewChild('dynamicComponent', { read: ViewContainerRef }) myRef: ViewContainerRef;
    constructor(
        private componentFactoryResolver: ComponentFactoryResolver,
        private eventService: EventService,
        private appGlobalService: AppGlobalService,
        public tabService: TabsService) {
    }
    ngOnInit() {
        this.eventService.eventEmit.on('refreshSubTabContainer', () => {
            this.refreshComponent();
        });

        if (this.appGlobalService.eventService.eventEmit.listenerCount("updateTagsDataSub1" + localStorage.getItem('currentPath')) > 0) {
            this.appGlobalService.eventService.eventEmit.removeListener("updateTagsDataSub1" + localStorage.getItem('currentPath'));
          }
        this.appGlobalService.eventService.eventEmit.on("updateTagsDataSub1" + localStorage.getItem('currentPath'),res =>{
            console.log("currentPath:" + localStorage.getItem('currentPath'))
            this.updateTagsData();
        });
    }
    // tslint:disable-next-line:use-life-cycle-interface
    ngOnChanges(changes: SimpleChanges): void {
        this.myRef.clear();
        this.loadComponent();
    }

    updateTagsData() {

        let temArray:any = [];

        for (let i = 0; i < this.myRef.length; i++){
            const tagInstance = this.myRef.get(i)["_view"].nodes[1].instance;
            if (tagInstance.tagData && tagInstance.tagData.shellDataId && tagInstance.tagData.shellDataId !== "0") {
                if (this.appGlobalService.getShellData(tagInstance.tagData.shellDataId)) {
                    // tagInstance.tagData = this.getDemoData();
                    if (this.appGlobalService.getShellData(tagInstance.tagData.shellDataId).remove === "true"){
                        temArray.push(this.myRef.get(i));
                    } else {
                        tagInstance.tagData = this.appGlobalService.getShellData(tagInstance.tagData.shellDataId);
                    }

                  }
            }

        }
        if (temArray.length > 0 ) {
            temArray.forEach(element => {
                const index = this.myRef.indexOf(element)
                if (index >= 0) {
                    this.myRef.remove(index);
                    this.appGlobalService.deleteShellData(element["_view"].nodes[1].instance.tagData.shellDataId);
                    console.log("page appAnchor  remove tag:"+ element["_view"].nodes[1].instance.tagData.shellDataId);
                }
            });
        }
    }


    refreshComponent() {
        const storeTagData = JSON.parse(localStorage.getItem("dataMapSubContainer"));
        if (storeTagData !== undefined && storeTagData !== null) {
            this.subComs = [];
            setTimeout(() => {
                // const style = storeTagData.style;
                const cDataObj = storeTagData.currentData;
                const tags = cDataObj.tags;
                if (tags !== undefined && tags.length > 0) {
                    const len = tags.length;
                    for (let i = 0; i < len; i++) {
                        const tag = tags[i];
                        this.tabService.getComsDataByStyle(tag.style, callData => {
                            if (callData) {
                                this.subComs.push(callData);
                            }
                        }, tag);
                    }
                }
                localStorage.removeItem("dataMapSubContainer");
                if (this.subComs !== undefined) {
                    const l = this.subComs.length;
                    this.myRef.clear();
                    for (let j = 0; j < l; j++) {
                        const v = this.subComs[j];
                        const factory = this.componentFactoryResolver.resolveComponentFactory(v.component);
                        const ref = this.myRef.createComponent(factory);
                        ref.instance.tagData = v.tagData;
                        ref.changeDetectorRef.detectChanges();
                    }
                }
            }, 50);
        }
    }
     loadComponent() {
        this.myRef.clear();
        const len = this.subComs.length;
        for (let i = 0; i < len; i++) {
            const v = this.subComs[i];
            const factory = this.componentFactoryResolver.resolveComponentFactory(v.component);
            const ref = this.myRef.createComponent(factory);
            ref.instance.tagData =this.changData(v.tagData, v);
        }
    }

    changData(tagData,v) {
        if (tagData.shellDataId && tagData.shellDataId !== "0") {

          if (this.appGlobalService.getShellData(tagData.shellDataId)) {
            v.tagData = this.appGlobalService.getShellData(tagData.shellDataId);
            this.appGlobalService.deleteShellData(tagData.shellDataId);
            return v.tagData; // this.appGlobalService.getShellData(tagData.shellDataId);
          } else {
            return tagData;
          }
    
        } else {
          return tagData;
        }
    }
}
